package com.neusoft.databus.core.repository;

import java.util.Date;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.neusoft.databus.common.model.MonitorData;

/**
 * @author naxiang
 */
public interface MonitorDataRepository extends JpaRepository<MonitorData, Long>, CustomizedMonitorDataRepository {

    List<MonitorData> findFirst10ByResourceCodeOrderByCollectedTimeDesc(String resourceCode);

    List<MonitorData> findFirst20ByResourceCodeOrderByCollectedTimeDesc(String resourceCode);

    List<MonitorData> findFirst50ByResourceCodeOrderByCollectedTimeDesc(String resourceCode);

    List<MonitorData> findFirst100ByResourceCodeOrderByCollectedTimeDesc(String resourceCode);

    List<MonitorData> findFirst200ByResourceCodeOrderByCollectedTimeDesc(String resourceCode);

    List<MonitorData> findFirst500ByResourceCodeOrderByCollectedTimeDesc(String resourceCode);

    List<MonitorData> findFirst1000ByResourceCodeOrderByCollectedTimeDesc(String resourceCode);

    @Override
    void deleteById(Long id);

    void deleteByResourceCode(String resourceCode);

    @Query(value = "SELECT a.* FROM monitor_data a RIGHT JOIN ( SELECT resource_code, Max(collected_time) AS collected_time FROM monitor_data WHERE resource_code IN (:resourceCodes) AND collected_time >= :startTime AND collected_time <= :endTime GROUP BY resource_code ) b ON a.resource_code = b.resource_code AND a.collected_time = b.collected_time WHERE a.resource_code IN (:resourceCodes) AND a.collected_time >= :startTime\r\n"
            +
            "  AND a.collected_time <= :endTime", nativeQuery = true)
    List<MonitorData> searchLatestData(@Param("resourceCodes") List<String> resourceCodes,
            @Param("startTime") Date startTime,
            @Param("endTime") Date endTime);

    @Query(value = "SELECT a.* FROM monitor_data a RIGHT JOIN ( SELECT resource_code, Min(collected_time) AS collected_time FROM monitor_data WHERE resource_code IN (:resourceCodes) AND collected_time >= :startTime AND collected_time <= :endTime GROUP BY resource_code ) b ON a.resource_code = b.resource_code AND a.collected_time = b.collected_time WHERE a.resource_code IN (:resourceCodes) AND a.collected_time >= :startTime\r\n"
            +
            "  AND a.collected_time <= :endTime", nativeQuery = true)
    List<MonitorData> searchOldestData(@Param("resourceCodes") List<String> resourceCodes,
            @Param("startTime") Date startTime,
            @Param("endTime") Date endTime);

    long countByResource_codeAndCreateTimeBetween(String resourceCode, Date start, Date end);

}
